<template>
  <el-dialog
    v-model="visible"
    title="互斥设置"
    width="600px"
    :before-close="handleClose"
  >
    <div class="mutex-config">
      <!-- 启用互斥开关 -->
      <el-form-item label="启用互斥">
        <el-switch
          v-model="localConfig.enabled"
          @change="val => handleEnableChange(!!val)"
        />
      </el-form-item>

      <!-- 互斥规则配置 -->
      <div v-if="localConfig.enabled" class="mutex-rules">
        <div class="rules-header">
          <h4>互斥规则</h4>
          <el-button type="primary" size="small" @click="addRule">
            添加规则
          </el-button>
        </div>

        <div v-for="(rule, index) in localConfig.rules" :key="index" class="rule-item">
          <div class="rule-header">
            <span>规则 {{ index + 1 }}</span>
            <el-button type="danger" size="small" @click="removeRule(index)">
              删除
            </el-button>
          </div>

          <div class="rule-content">
            <!-- 选择值 -->
            <el-form-item label="当选择值">
              <el-select
                v-model="rule.value"
                placeholder="选择值"
                style="width: 200px"
              >
                <el-option
                  v-for="option in componentOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>

            <!-- 隐藏组件 -->
            <el-form-item label="隐藏组件">
              <el-select
                v-model="rule.hiddenComponents"
                multiple
                placeholder="选择要隐藏的组件"
                style="width: 100%"
              >
                <el-option
                  v-for="component in availableComponents"
                  :key="component.id"
                  :label="getComponentLabel(component)"
                  :value="component.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { MutexConfig, CanvasComponent, Option } from '../types'

interface Props {
  modelValue: boolean
  mutexConfig: MutexConfig
  componentOptions: Option[]
  allComponents: CanvasComponent[]
  currentComponent: CanvasComponent | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [config: MutexConfig]
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const localConfig = ref<MutexConfig>({
  enabled: false,
  rules: []
})

// 可用的组件列表（排除当前组件）
const availableComponents = computed(() => {  
  const currentComponent = props.currentComponent || null
  const allComps = props.allComponents || []  

  // 获取栅格中的子组件
  let gridComponents = allComps.filter(com => com.type == 'grid')
  console.log('gridComponents', gridComponents)
  let childComponents = [] as CanvasComponent[]
  gridComponents.forEach(grid => {
    if (grid.children) {  
      childComponents.push(...grid.children)
    }
  })

  // 获取非栅格组件
  let itemComponents = allComps.filter(com => com.type != 'grid' && !com.parentId)
  console.log('itemComponents', itemComponents)

  // 合并栅格和非栅格组件并排除当前组件
  return [...childComponents, ...itemComponents].filter(com => com.id != currentComponent?.id)
})

// 生成组件显示标签
const getComponentLabel = (component: CanvasComponent): string => {
  const label = component.props.label || component.props.field
  const type = component.type
  const field = component.props.field
  
  // 如果有标题，显示标题和字段名
  if (component.props.label) {
    return `${label} (${field})`
  }
  
  // 否则显示类型和字段名
  return `${type} (${field})`
}

// 监听props变化，更新本地配置
watch(() => props.mutexConfig, (newConfig) => {
  localConfig.value = JSON.parse(JSON.stringify(newConfig))
}, { immediate: true, deep: true })

// 启用/禁用互斥
const handleEnableChange = (enabled: boolean) => {
  localConfig.value.enabled = enabled
  if (!enabled) {
    localConfig.value.rules = []
  }
}

// 添加规则
const addRule = () => {
  localConfig.value.rules.push({
    value: '',
    hiddenComponents: []
  })
}

// 删除规则
const removeRule = (index: number) => {
  localConfig.value.rules.splice(index, 1)
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}

// 确认设置
const handleConfirm = () => {
  emit('confirm', localConfig.value)
  visible.value = false
}
</script>

<style scoped lang="scss">
.mutex-config {
  .mutex-rules {
    margin-top: 20px;
    
    .rules-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h4 {
        margin: 0;
      }
    }
    
    .rule-item {
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 16px;
      margin-bottom: 16px;
      
      .rule-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        font-weight: 500;
      }
      
      .rule-content {
        .el-form-item {
          margin-bottom: 12px;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style> 